package com.gw.booking.service;

import com.gw.booking.dto.wechat.OrderTimeDto;
import com.gw.booking.entity.OrderTime;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

@Service
public class OrderTimeService {
    @Autowired
    private SessionFactory sessionFactory;

    /**
     * 添加预约时间
     * @param session
     * @param orderTimeDtoList
     * @param orderId
     */
    public void txAddOrderTimes(Session session, List<OrderTimeDto> orderTimeDtoList, Integer orderId){
        //删除旧预约时间集合
        String sql = "delete from order_time where order_id = :orderId ";
        session.createSQLQuery(sql).setParameter("orderId",orderId).executeUpdate();
        //新增新预约时间
        for(OrderTimeDto orderTimeDto : orderTimeDtoList){
            OrderTime orderTime = new OrderTime();
            orderTime.setOrderId(orderId);
            orderTime.setOrderDate(orderTimeDto.getOrderDate());
            orderTime.setOrderTime(new Timestamp(orderTimeDto.getOrderTime().getTime()));
            session.save(orderTime);
        }
    }

    /**
     * 获取预约时间集合
     * @param session
     * @param orderId
     * @return
     */
    public List<OrderTimeDto> getOrderTimeList(Session session, Integer orderId){
        String sql = " select order_date as orderDate, order_time as orderTime from order_time " +
                " where order_id = :orderId ";
        List<OrderTimeDto> orderTimeDtoList = session.createSQLQuery(sql)
                .setParameter("orderId", orderId)
                .setResultTransformer(Transformers.aliasToBean(OrderTimeDto.class))
                .list();
        return orderTimeDtoList;
    }
}
